package xp2p.conf;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import xp2p.conf.jxta.JxtaConfigurator;

import net.jxta.id.IDFactory;
import net.jxta.peer.PeerID;
import net.jxta.peergroup.PeerGroupID;
import net.jxta.platform.NetworkConfigurator;
import net.jxta.platform.NetworkManager;
import net.jxta.platform.NetworkManager.ConfigMode;

public class BasicConfiguration
{
	public int TcpPort = 9701;
	public int ConnectTimeout = 120000;
	public int HttpPort = 9700;
	public File HomeDir = new File(".cache");
	public File FileHomeDir = new File(".transfer");
	public UUID MyPeerId = UUID.randomUUID();
	public UUID MyPeerGroupId = UUID.randomUUID();
	public String Name = "Basic xp2p peer";
	public String DefaultNetGroupName = "Network group";
	public boolean Relay = false;
	public boolean Rendezvous = true;
	public boolean Http = false;
	public boolean Tcp = true;
	public URI StartURI;
	public long filesPublishinglifetime = 120000L; // 2 minutes
	
	private IConfigurator[] _configurators = { new JxtaConfigurator()};

	public NetworkManager Build() throws IOException
	{
		ConfigMode conf;
		PeerGroupID gid = IDFactory.newPeerGroupID(DefaultNetGroupName.getBytes());
		PeerID pid = IDFactory.newPeerID(gid, MyPeerId.toString().getBytes());
		if (Relay && Rendezvous)
		{
			conf = ConfigMode.RENDEZVOUS_RELAY;
		} else if (Relay)
		{
			conf = ConfigMode.RELAY;
		} else if (Rendezvous)
		{
			conf = ConfigMode.RENDEZVOUS;
		} else
		{
			conf = ConfigMode.EDGE;
		}
		NetworkManager.RecursiveDelete(FileHomeDir);
		NetworkManager.RecursiveDelete(HomeDir);
		NetworkManager result = new NetworkManager(conf, Name, HomeDir.toURI());
		NetworkConfigurator cfg = result.getConfigurator();
		cfg.setTcpPort(TcpPort);
		cfg.setTcpEnabled(Tcp);
		cfg.setTcpIncoming(Tcp);
		cfg.setTcpOutgoing(Tcp);
		cfg.setTcpOutgoing(Tcp);
		cfg.setUseMulticast(false);
		cfg.setHttpEnabled(false);
		cfg.setInfrastructureID(gid);
		cfg.setPeerID(pid);
		if (conf == ConfigMode.RELAY || conf == ConfigMode.RENDEZVOUS_RELAY)
		{
			cfg.setHttpEnabled(Http);
			cfg.setHttpOutgoing(true);
			cfg.setHttpIncoming(true);
			cfg.setHttpPort(HttpPort);
		}
		cfg.addSeedRendezvous(StartURI);
		result.setConfigPersistent(false);
		Logger logger = Logger.getLogger(this.getClass().getName());
		logger.log(Level.INFO, cfg.getInfrastructureDescriptionStr());
		
		for (IConfigurator c : _configurators)
		{
			c.Configure();
		}
		
		return result;
	}
}
